/**
 * @description 用户的api相关接口
 * @author 宫彦胜
 */ 
const router = require('koa-router')()

const { isExist, register, login, deleteCurUser } = require('../../controller/user')
const genValidator = require('../../middlewares/validator')
const userValidate = require('../../validator/user')
const { isTest } = require('../../util/env')
const { loginCheck } = require('../../middlewares/loginChecks')

// 定义访问的前缀
router.prefix('/api/user')


/**
 * @description 注册功能
 */
router.post('/register', genValidator(userValidate) ,async (ctx,next)=>{
  // 获取参数
  const { userName, password, gender } = ctx.request.body
  // 收集参数向后端进行传递保存了
  
  ctx.body = await register({ userName, password, gender })
})

/**
 * 根据用户名查询是否存在
 */
router.post('/isExist', async (ctx,next)=>{
  // 获取到用户的信息来判断
  const { userName } = ctx.request.body
  ctx.body = await isExist(userName)
})

/**
 * 登录
 */
router.post('/login', async (ctx, next)=>{
  const { userName, password } = ctx.request.body
  ctx.body = await login(ctx, userName, password)
})

/**
 * 删除用户 , 添加登录中间件
 */
router.post('/delete', loginCheck ,async (ctx, next)=>{
  // 如果是test 环境才生效
  if(isTest){
    // 获取自身session 
    const { userName } = ctx.session.userInfo
    ctx.body = await deleteCurUser(userName)
  }
})




module.exports = router